package com.ztools.pc.job;

import com.ztools.common.model.pc.coupon.CouponExpire;
import com.ztools.common.model.pc.coupon.CouponRecord;
import com.ztools.pc.service.coupon.CouponExpireService;
import com.ztools.pc.service.coupon.CouponRecordService;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: seeTools
 * @Date: 2023/5/18  11:17
 * @Version 1.0
 */
@Component
public class CouponJob {

    @Resource
    private CouponRecordService couponRecordService;
    @Resource
    private CouponExpireService couponExpireService;


    /**
     * 优惠券过期定时任务
     */
    @Scheduled(cron = "0 0/15 * * * ?")
    @SchedulerLock(name = "couponExpireJob", lockAtLeastFor = "15m", lockAtMostFor = "16m")
    public void couponExpireJob() {
        // 1. 查询出过期的优惠券
        List<CouponRecord> expireCouponList = couponRecordService.findExpireCoupon();
        List<CouponExpire> couponExpireList = new ArrayList<>();
        // 2.存入过期表中
        if (expireCouponList.size() > 0) {
            for (CouponRecord couponRecord : expireCouponList) {
                CouponExpire couponExpire = CouponExpire.builder()
                        .templateId(couponRecord.getTemplateId())
                        .couponType(couponRecord.getCouponType())
                        .memberId(couponRecord.getMemberId())
                        .startDate(couponRecord.getStartDate())
                        .endDate(couponRecord.getEndDate())
                        .expireTime(new Date())
                        .build();
                couponExpireList.add(couponExpire);
            }
            couponExpireService.saveBatch(couponExpireList);
            // 3.删除记录表里面的数据(物理删除)
            couponRecordService.deleteBatch(expireCouponList);
        }
    }
}
